package message.messageFactory;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import message.AddServerRequestMessage;
import message.AddServerResponseMessage;
import message.AuthenticationRequestMessage;
import message.AuthenticationResponseMessage;
import message.BulkUpdateRequestMessage;
import message.BulkUpdateResponseMessage;
import message.InsertDataRequestMessage;
import message.InsertDataResponseMessage;
import message.Message;
import message.PingClientResponseMessage;
import message.RestartServerRequestMessage;
import message.ShutDownServerRequestMessage;
import message.UpdateDataResponseMessage;
import message.PingRequestMessage;
import message.PingServerResponseMessage;
import message.RestartServerResponseMessage;
import message.ShutDownServerResponseMessage;
import message.UpdateDataRequestMessage;

import org.xml.sax.InputSource;

public class MessageFactory
{
	private final JAXBContext context;
	private static MessageFactory factory;
	
	private MessageFactory() throws InstantiationException
	{
		try
		{
			this.context = JAXBContext.newInstance(AddServerRequestMessage.class, AddServerResponseMessage.class, AuthenticationRequestMessage.class, AuthenticationResponseMessage.class, 
					InsertDataRequestMessage.class, InsertDataResponseMessage.class, Message.class, PingClientResponseMessage.class, PingRequestMessage.class, PingServerResponseMessage.class, 
					RestartServerRequestMessage.class, RestartServerResponseMessage.class, ShutDownServerRequestMessage.class, ShutDownServerResponseMessage.class, UpdateDataRequestMessage.class, 
					UpdateDataResponseMessage.class, BulkUpdateRequestMessage.class, BulkUpdateResponseMessage.class);
		}
		catch (JAXBException e) {  e.printStackTrace(); throw new InstantiationException(); }
	}
	
	public static MessageFactory getInstance()
	{
		if (factory == null)
			try
			{
				factory = new MessageFactory();
			}
			catch (InstantiationException e)
			{
				e.printStackTrace();
			}
		
		return factory;
	}
	public String serializeMessage(Message message)
	{
		StringWriter writer = new StringWriter();
		
		try
		{
			Marshaller marshaller = context.createMarshaller();
			
			marshaller.marshal(message, writer);
		}
		catch (JAXBException e)
		{
			e.printStackTrace();
		}
		System.out.println(writer.toString());
		return writer.toString();
	}
	public Message unserializeMessage(String xml)
	{
		try
		{
			Unmarshaller unmarshaller = context.createUnmarshaller();
			
			if (xml != null)
				return (Message) unmarshaller.unmarshal(new InputSource(new StringReader(xml)));
		}
		catch (JAXBException e) {}
		
		return null;
	}
}
